package top.infopub.mgr.mkt.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.infopub.dto.mkt.AfterSummaryDto;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.BidCurrencyDomain;
import top.infopub.mgr.mkt.jsonvo.AfterSummaryJsonVo;
import top.infopub.mgr.mkt.service.BidOpenResultService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.vo.BidCurrencyVo;
import top.infopub.model.mkt.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Warking
 * @Date 2021/4/27 16:09
 * @Version 1.0
 */
@Service
public class BidOpenResultServiceImpl implements BidOpenResultService {
    @Autowired
    private BidOpenResultDao bidOpenResultDao;

    @Autowired
    private AfterSummaryBidDao afterSummaryBidDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private BidInfoDao bidInfoDao;
    @Autowired
    private ProProcessManageService proProcessManageService;
    @Autowired
    private AfterSummaryRankDao afterSummaryRankDao;
    @Autowired
    private BusinessDetailsDao businessDetailsDao;
    @Autowired
    private OAFlowService oaFlowService;

    public Page<BidCurrencyDomain> selectPage(Page<BidCurrencyDomain> page, BidCurrencyVo bidCurrencyVo) throws ParseException {
        //处理时间范围
        if (!StringUtils.isEmpty(bidCurrencyVo.getDates()))
        {
            String[] splitTime = bidCurrencyVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            bidCurrencyVo.setStartDate(format.parse(splitTime[0]));
            bidCurrencyVo.setEndDate(format.parse(splitTime[1]));
        }

        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        return  (Page<BidCurrencyDomain>)bidOpenResultDao.selectByDomainWhere(bidCurrencyVo);
    }

    @Override
    public AfterSummaryJsonVo queryDetailById(String id) {
        AfterSummaryJsonVo  summaryJsonVo = new AfterSummaryJsonVo();
        AfterSummaryDto afterSummaryDto = bidOpenResultDao.queryDetailById(id);
         summaryJsonVo.setInfo(afterSummaryDto);
        List<AfterSummaryRank> afterSummaryRanks = afterSummaryRankDao.selectByAfterSummaryId(afterSummaryDto.getId());
        summaryJsonVo.setAfterSummRankList(afterSummaryRanks);
        //中标单位报价
        List<AfterSummaryBid> afterSummBidList = afterSummaryBidDao.selectByAfterSummaryId(afterSummaryDto.getId());
        summaryJsonVo.setAfterSummBidList(afterSummBidList);
        if (afterSummBidList==null || afterSummBidList.size()==0){
            List<AfterSummaryBid> afterSummary = new ArrayList<>();
            List<BusinessDetails> businessDetails = businessDetailsDao.selectByProCode(afterSummaryDto.getProCode());
            for (BusinessDetails businessDetail : businessDetails) {
                 AfterSummaryBid afterSummaryBid = new AfterSummaryBid();
                 afterSummaryBid.setBidName(businessDetail.getTenderOfferItem());
                afterSummary.add(afterSummaryBid);
            }
            summaryJsonVo.setAfterSummBidList(afterSummary);
        }
        //附件信息
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(afterSummaryDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE27.getCode(), null);
        summaryJsonVo.setFileAtt(fileAttaListToArray(projectAttaList));
        return summaryJsonVo;
    }

    @Override
    public RspVo saveAll(AuthorizationVO vo, AfterSummaryDto info, List<AfterSummaryRank> afterSummaryRanks, List<AfterSummaryBid> afterSummBidList, List<ProjectAttachment> attachmentList,Integer submitType,String bodyStr) {

        AuthorizationVO user = SessionUserUtils.getSessionAttributeForUserDtl();
        //查询开标结果信息
        BidOpenResult bidOpenResult = bidOpenResultDao.selectById(info.getId());
        bidOpenResult.setId(info.getId());
        //查询投标信息
        BidInfo bidInfo = bidInfoDao.queryByProCode(bidOpenResult.getProCode());
        int i = new Date().compareTo(bidInfo.getBidEndDate());
        if (i == -1){
            return RspVo.getFailureResponse(400, "该项目还未开标不可编辑");
        }
        if ("0".equals(bidOpenResult.getBiddingStatus())){//0-投标中
            return RspVo.getFailureResponse(400, "该项目还在投标中不可编辑");
        }
        if ("1".equals(bidOpenResult.getProcessStatus()) || "9".equals(bidOpenResult.getProcessStatus())){
            return RspVo.getFailureResponse(400, "审批中或审批通过不能编辑");
        }

        afterSummaryRankDao.deleteBySummaryId(info.getId());//删除原来的开标记录
       //更新开标记录
        afterSummaryRankDao.insertByBatch(afterSummaryRanks);

        //更新报价记录
        afterSummaryBidDao.deleteBySummaryId(info.getId());
        for (AfterSummaryBid afterSummaryBid : afterSummBidList) {
            afterSummaryBid.setAfterSummaryId(info.getId());
        }
        afterSummaryBidDao.insertByBatch(afterSummBidList);

        //更新附件信息
        projectAttachmentDao.deleteByWhere(bidOpenResult.getProCode(), ProjectFileTypeEnum.FILE_TYPE27.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        //更新开标结果信息
        bidOpenResult.setUptBy(vo.getId());
        bidOpenResult.setUptTime(new Date());
        bidOpenResult.setBidding(info.getBidding());
        bidOpenResultDao.updateById(bidOpenResult);

        if (submitType == 1){  //发起审批流程
            //处理OA待办信息
            if (StringUtils.isNotBlank(bidOpenResult.getOaId())) {
                oaFlowService.finishOA(bidOpenResult.getOaId());
            }
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE10,bodyStr,bidOpenResult.getId(),bidOpenResult.getProCode(),user);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public BidOpenResult selectById(String id) {
        return bidOpenResultDao.selectById(id);
    }

    private String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }

}
